package com.example.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.config.JwtConfig;
import com.example.user_model.entity.User;
import com.example.user.mapper.UserMapper;
import com.example.user.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 用户信息 服务实现类
 * </p>
 *
 * @author sjz
 * @since 2024-07-10
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private JwtConfig jwtConfig;

    @Override
    public String login(String phone, String code) {
        //优化: 与redis缓存中的验证码进行比对
        String codeInRedis = (String) redisTemplate.opsForValue().get(phone);
        if (codeInRedis != null && codeInRedis.equals(code)) {
            //如果比对成功,即登录成功
            //判断当前用户是否为新用户
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone, phone);
            User user = this.getOne(queryWrapper);
            if (user == null) {
                //如果是新用户,自动完成注册(存在user表中)
                user = new User();
                user.setPhone(phone);
                this.save(user);
            }

            //优化:如果用户登录成功,就删除redis中的验证码,因为已经不需要了
            redisTemplate.delete(phone);
            //下发JWT令牌
            String token = JwtUtils.createJwt(
                    null,
                    phone,
                    null,
                    jwtConfig.getTtl(),
                    jwtConfig.getKey()
            );

            log.info("token:{}", token);
            return token;
        }
        return null;

    }

    @Override
    public String validate(String token) {

        log.info("token:{}", token);

        if (!JwtUtils.validateToken(token, jwtConfig.getKey())) {
            throw new RuntimeException("token失效");
        }

        Claims claims = JwtUtils.parseJwt(token, jwtConfig.getKey());
        return claims.get("adminId", String.class);
    }
}

